const { moment, moment_comment, moment_like, blog_user } = require('@/model');
const Sequelize = require('sequelize');

class MomentService {
  async addMoment({ user_id, content, images }) {
    return await moment.create({ user_id, content, images });
  }

  async getMomentList({ pageIndex, pageSize, user_id }) {
    const offset = (pageIndex - 1) * pageSize;
    const includeOptions = [
      { model: blog_user, as: 'author', attributes: ['id', 'nickname', 'avatar', "username"] }
    ];
    if (user_id) {
      includeOptions.push({
        model: moment_like,
        as: 'likes',
        where: { user_id },
        required: false,
        // attributes: []
      });
    }

    const { count, rows } = await moment.findAndCountAll({
      include: includeOptions,
      order: [['createdAt', 'DESC']],
      limit: Number(pageSize),
      offset: Number(offset),
    });
    const list = rows.map(row => {
      const data = row.get({ plain: true }); // 获取原始数据
      console.log('data原始数据', data);
      data.is_like = data.likes && data.likes.length > 0;
      delete data.likes;
      return data;
    });
    return { total: count, list };
  }

  async getMomentDetail(id, user_id) {
    let moment = await moment.findByPk(id, {
      include: [
        { model: blog_user, as: 'author', attributes: ['id', 'nickname', 'avatar',"username"] },
        {
          model: moment_like, as: 'likes', where: { user_id },
          required: false,
        },
        {
          model: moment_comment,
          as: 'comments',
          include: [
            { model: blog_user, as: 'commenter', attributes: ['id', 'nickname', 'avatar', 'username'] },
            { model: moment_comment, as: 'replyToComment', attributes: ['id', 'content', 'user_id'] }
          ]
        }
      ]
    });
    if (!moment) return null;

    const data = moment.get({ plain: true }); // 获取纯对象，避免循环引用
    data.is_like = !!(data.likes && data.likes.length);

    // 删除冗余字段
    delete data.likes;

    return data;
  }

  async likeMoment({ user_id, moment_id }) {
    await moment_like.findOrCreate({ where: { user_id, moment_id } });
    await moment.increment('like_count', { by: 1, where: { id: moment_id } });
    return await this.getMomentDetail(moment_id, user_id);
  }

  async unlikeMoment({ user_id, moment_id }) {
    await moment_like.destroy({ where: { user_id, moment_id } });
    await moment.decrement('like_count', { by: 1, where: { id: moment_id } });
    return await this.getMomentDetail(moment_id, user_id);
  }

  async addComment({ user_id, moment_id, content, reply_id }) {
    await moment_comment.create({ user_id, moment_id, content, reply_id });
    await moment.increment('comment_count', { by: 1, where: { id: moment_id } });
  }

  async getCommentList({ moment_id, offset = 0, size = 10 }) {
    const { count, rows } = await moment_comment.findAndCountAll({
      where: { moment_id },
      include: [
        { model: blog_user, as: 'commenter', attributes: ['id', 'nickname', 'avatar', 'username'] },
        {
          model: moment_comment,
          as: 'replyToComment',
          attributes: ['id', 'content', 'user_id'],
          include: [
            { model: blog_user, as: 'commenter', attributes: ['id', 'nickname', 'avatar', 'username'] },
          ]
        }
      ],
      order: [['createdAt', 'DESC']],
      // limit: Number(size),
      // offset: Number(offset),
    });
    return { total: count, list: rows };
  }

  async deleteComment(id) {
    const comment = await moment_comment.findByPk(id);
    if (comment) {
      await moment.decrement('comment_count', { by: 1, where: { id: comment.moment_id } });
      await comment.destroy();
    }
  }

  async deleteMoment(id) {
    await moment.destroy({ where: { id } });
    await moment_comment.destroy({ where: { moment_id: id } });
    await moment_like.destroy({ where: { moment_id: id } });
  }
}

module.exports = new MomentService();